
package com.scs.application.modules.settlement.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Maps;
import com.scs.application.core.export.ExportParamDto;
import com.scs.application.core.model.CommonResult;
import com.scs.application.core.model.PageResult;
import com.scs.application.core.model.RestResult;
import com.scs.application.core.mvc.controller.CrudController;
import com.scs.application.core.mvc.controller.ImAndExAbleController;
import com.scs.application.core.pdf.PdfExportUtils;
import com.scs.application.core.pdf.entity.PdfExportParams;
import com.scs.application.core.pdf.enums.PdfPageDirection;
import com.scs.application.core.pdf.enums.SpacingMode;
import com.scs.application.core.utils.FileUtils;
import com.scs.application.core.utils.FreeMarkers;
import com.scs.application.core.utils.UserUtils;
import com.scs.application.modules.design.service.QueryGenerator;
import com.scs.application.modules.settlement.entity.DeptOprtUse;
import com.scs.application.modules.settlement.entity.DeptOprtUseItem;
import com.scs.application.modules.settlement.mapper.DeptOprtUseMapper;
import com.scs.application.modules.settlement.request.DeptOprtUseItemQueryRequest;
import com.scs.application.modules.settlement.request.DeptOprtUseQueryRequest;
import com.scs.application.modules.settlement.service.DeptOprtUseItemService;
import com.scs.application.modules.settlement.service.DeptOprtUseService;
import lombok.AllArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 病人消耗主单 controller
 */
@AllArgsConstructor
@RestController
@RequestMapping("/settlement/dept_oprt_uses")
public class DeptOprtUseController extends CrudController<DeptOprtUse, String, DeptOprtUseService> implements ImAndExAbleController<DeptOprtUseQueryRequest> {

    private final DeptOprtUseItemService deptOprtUseItemService;
    private final DeptOprtUseMapper deptOprtUseMapper;

    @GetMapping("/page")
    public PageResult page(DeptOprtUseQueryRequest request) {
        IPage page = service.page(request);
        return PageResult.ok("查询成功", page.getRecords(), page.getTotal());
    }

    @GetMapping("/list")
    public CommonResult list(DeptOprtUseQueryRequest request) {
        List<DeptOprtUse> list = service.list(request);
        return CommonResult.ok("查询成功", list);
    }

    /**
     * PDF打印预览
     *
     * @param id
     * @param response
     */
    @GetMapping("/{id}/pdf-preview")
    public void pdfPreview(@PathVariable(name = "id") String id,
                           @RequestParam(name = "direction", required = false, defaultValue = "transverse") String direction,
                           @RequestParam(name = "spacingMode", required = false, defaultValue = "normal") String spacingMode,
                           @RequestParam(name = "pageSize", required = false, defaultValue = "A4") String pageSize,
                           @RequestParam(name = "perRowsOfGrid", required = false, defaultValue = "5") int perRowsOfGrid,
                           HttpServletResponse response) throws IOException {

        DeptOprtUse deptOprtUse = service.getById(id);
        if (deptOprtUse == null) {
            return;
        }
        deptOprtUse.setSupplierName(UserUtils.getSupplier().getName());
        PdfPageDirection pageDirection = PdfPageDirection.of(direction);
        SpacingMode sMode = SpacingMode.of(spacingMode);

        List<DeptOprtUseItem> items = deptOprtUseItemService.list(new DeptOprtUseItemQueryRequest().setDeptOprtUseId(id));
        Double subtotalAmount = 0.0;
        if (!items.isEmpty()) {
            subtotalAmount = items.stream().collect(Collectors.summingDouble(DeptOprtUseItem::getAmount));
        }
        deptOprtUse.setAmount(subtotalAmount);
        String path = String.format("print-template/dept_oprt_use/%s.json", pageSize.toUpperCase());
        String templateJson = FileUtils.readClassPathFileToString(path, "UTF-8");
        response.setContentType(MediaType.APPLICATION_PDF_VALUE);
        response.addHeader("Content-Disposition", String.format("filename=%s.pdf", URLEncoder.encode("病人消耗单-" + deptOprtUse.getBusKey())));

        Map<String, Object> map = Maps.newHashMap();
        map.put("oprtUse", deptOprtUse);

        templateJson = FreeMarkers.renderString(templateJson, map);
        PdfExportParams exportParams = PdfExportParams.fromJson(templateJson);

        exportParams.setSpacingMode(sMode);
        exportParams.setPageDirection(pageDirection);
        exportParams.setPerRowsOfGrid(perRowsOfGrid);
        exportParams.setGridData(items);

        PdfExportUtils.export(response.getOutputStream(), exportParams);
    }


    /***
     * @param request
     * @Description:  品名品规厂商汇总
     */
    @GetMapping("/pageSum")
    public PageResult pageSum(HttpServletRequest request, DeptOprtUse entity) {
        IPage<DeptOprtUse> page = QueryGenerator.parsePage(request);
        QueryWrapper<DeptOprtUse> queryWrapper = QueryGenerator.initQueryWrapper(request);
        fillQueryAuth(queryWrapper,entity);
        if (UserUtils.isSupplier()) {
            queryWrapper.eq("supplier_id",UserUtils.getSupplierId());
        }
        IPage pageResult = deptOprtUseMapper.pageSum(page, queryWrapper);
        return PageResult.ok("查询成功", pageResult.getRecords(), pageResult.getTotal());
    }


    /***
     * @param request
     * @Description:  品名汇总
     */
    @GetMapping("/pageSumByMatrName")
    public PageResult pageSumByMatrName(HttpServletRequest request, DeptOprtUse entity) {
        IPage<DeptOprtUse> page = QueryGenerator.parsePage(request);
        QueryWrapper<DeptOprtUse> queryWrapper = QueryGenerator.initQueryWrapper(request);
        fillQueryAuth(queryWrapper,entity);
        if (UserUtils.isSupplier()) {
            queryWrapper.eq("supplier_id",UserUtils.getSupplierId());
        }
        IPage pageResult = deptOprtUseMapper.pageSumByMatrName(page, queryWrapper);
        return PageResult.ok("查询成功", pageResult.getRecords(), pageResult.getTotal());
    }


    @GetMapping("/exportDataByMatrName")
    public RestResult exportDataByMatrName(@RequestParam Map<String, String> reqData, HttpServletRequest request, DeptOprtUse entity) throws Exception {
        QueryWrapper<DeptOprtUse> queryWrapper = QueryGenerator.initQueryWrapper(request);
        fillQueryAuth(queryWrapper,entity);
        ExportParamDto exportParams = JSON.parseObject(JSON.toJSONString(reqData), ExportParamDto.class);
        Map<String, Object> userParam = null;
        //固定参数
        if (reqData.containsKey("userParam")) {
            JSONObject ob = JSON.parseObject(reqData.get("userParam") + "");
            userParam = Maps.newHashMap(ob);
        }
        return RestResult.ok("查询成功", service.exportFullDataByMatrName(queryWrapper, exportParams, userParam,request));
    }

}
